package autoteam.ui.tabs;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTable;

import autoteam.League;
import autoteam.Local;
import autoteam.tables.LeagueTableModel;
import autoteam.ui.AutoTeamTablePanel;
import autoteam.ui.dialogs.LeagueCreator;
import autoteam.ui.dialogs.LeagueEditor;

public class LeaguesTab extends TabPanel {
	private static final long serialVersionUID = 8402054886873012289L;

	private final JButton editButton = new JButton("Edit");
	private final JButton addButton = new JButton("Add");
	private final JButton removeButton = new JButton("Remove");
	private LeagueTableModel leagueModel;

	private JTable table;

	public LeaguesTab(JFrame parentFrame) // Tester: DO NOT USE
	{
		super();
		setButtonActions(parentFrame);
	}

	public LeaguesTab(League currentLeague, JFrame parentFrame) {
		super();
		setButtonActions(parentFrame);

		// create the league table
		leagueModel = new LeagueTableModel( currentLeague );
		final AutoTeamTablePanel theTablePanel = new AutoTeamTablePanel(
				leagueModel, editButton, addButton, removeButton);

		table = theTablePanel.getTable();
		this.add(theTablePanel);

	}

	public void changeLeague(League newLeague) {
		String inputValue = JOptionPane.showInputDialog(
				Local.get("Enter League"), newLeague.league);
		if (inputValue != null) {
			newLeague.setLeagueName(inputValue);
		}
	}
	
	protected void setButtonActions(final JFrame parentFrame)
	{
		addButton.addActionListener(new ActionListener()
		{
			@Override
			public void actionPerformed(ActionEvent e)
			{
				if (table.isEditing())
				{
					table.getCellEditor().stopCellEditing();
				}
				int j = table.getSelectedRow();
				leagueModel.fireTableDataChanged();

				// TODO remove setCurrentFrame after integration is Complete
				// RSMSController.setCurrentFrame( new JFrame() );
				LeagueCreator dialog = new LeagueCreator(parentFrame, leagueModel);
				dialog.setVisible(true);
			}
		});

		editButton.addActionListener(new ActionListener()
		{
			@Override
			public void actionPerformed(ActionEvent e)
			{
				// TODO remove setCurrentFrame after integration is Complete
				// RSMSController.setCurrentFrame( new JFrame() );
				LeagueEditor dialog = new LeagueEditor(parentFrame,leagueModel, table.getSelectedRow());
				dialog.setVisible(true);
			}
		});
		removeButton.addActionListener( new ActionListener() 
		{

			@Override
			public void actionPerformed(ActionEvent e)
			{
				// TODO Auto-generated method stub
				leagueModel.delete(table.getSelectedRow());
			}
			
		});
	}

}
